#ifndef SQUARETHREAD_H
#define SQUARETHREAD_H

#include <QObject>
#include <QThread>
#include <QPoint>

// 工作对象：实际在工作线程中运行
class SquareWorker : public QObject
{
    Q_OBJECT

public:
    explicit SquareWorker(QObject *parent = nullptr);
    void requestStop() { m_shouldStop = true; }

public slots:
    void doWork(const QPoint &topLeft, int sideLength);

signals:
    void pointGenerated(const QPoint &pt);
    void workFinished();

private:
    bool m_shouldStop;
};

// 主对象：始终在主线程，供QML使用
class SquareThread : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QPoint topLeft READ topLeft WRITE setTopLeft NOTIFY topLeftChanged)
    Q_PROPERTY(int sideLength READ sideLength WRITE setSideLength NOTIFY sideLengthChanged)
    Q_PROPERTY(bool running READ running NOTIFY runningChanged)

public:
    explicit SquareThread(QObject *parent = nullptr);
    ~SquareThread();

    QPoint topLeft() const { return m_topLeft; }
    void setTopLeft(const QPoint &topLeft) {
        if (m_topLeft != topLeft) {
            m_topLeft = topLeft;
            emit topLeftChanged();
        }
    }

    int sideLength() const { return m_sideLength; }
    void setSideLength(int sideLength) {
        if (m_sideLength != sideLength) {
            m_sideLength = sideLength;
            emit sideLengthChanged();
        }
    }

    bool running() const { return m_running; }

public slots:
    void start();
    void stop();

signals:
    void squarePoint(const QPoint &pt);
    void topLeftChanged();
    void sideLengthChanged();
    void runningChanged();
    void finished();

private slots:
    void onWorkerFinished();
    void onPointGenerated(const QPoint &pt);
    void onThreadStarted();

private:
    QPoint m_topLeft;
    int m_sideLength;
    QThread *m_thread;
    SquareWorker *m_worker;
    bool m_running;
    bool m_workStarted;  // 防止重复调用 doWork
};

#endif // SQUARETHREAD_H

